// translation.js

function translateText(texts, targetLanguage) {
	return new Promise((resolve, reject) => {
		const isSingleString = typeof texts === 'string';
		const textsArray = isSingleString ? [texts] : texts;

		const placeholders = [];
		const textsForTranslation = textsArray.map(text =>
			text.replace(/\{[^}]+:[^}]+\}|\[.+?\]/g, match => {
				placeholders.push(match);
				return `__PLACEHOLDER_${placeholders.length - 1}__`;
			})
		);
			
		if(!uni.$config.translate_key){
			reject('There is no translate_key');
			return
		}
		uni.request({
			url: `https://translation.googleapis.com/language/translate/v2?key=`+uni.$config.translate_key,
			method: "POST",
			header: {
				"Content-Type": "application/json"
			},
			data: {
				q: isSingleString ? textsForTranslation[0] : textsForTranslation,
				target: targetLanguage
			},
			success: (res) => {
				const data = res.data;
				
					console.log(data);
				const translationsArray = data.data.translations.map(translation =>
					translation.translatedText.replace(/__PLACEHOLDER_(\d+)__/g, (_, index) =>
						placeholders[index])
				);
				resolve(isSingleString ? translationsArray[0] : translationsArray);
			},
			fail: (err) => {
				console.error("翻译错误:", err);
				reject(err);
			}
		});
	});
}
// 将函数放入一个对象并默认导出
export default {
  translateText
};